package com.example.lp.basemvp.proxy;

import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleObserver;
import android.arch.lifecycle.OnLifecycleEvent;
import android.util.Log;

import com.example.lp.basemvp.annotation.InjectPresenter;
import com.example.lp.basemvp.baseview.IBaseView;
import com.example.lp.basemvp.presebter.BasePrsenter;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class MvpProxyIml<V extends IBaseView> implements IMvpProxy, LifecycleObserver {
    private static final String TAG="MvpProxyIml";
    private V mView;
    List<BasePrsenter> prsenterList;

    public MvpProxyIml(V view) {
        this.mView = view;
        prsenterList = new ArrayList<>();
    }

    @Override
    public void bindAndCreatePresenter() {
        Field[] fields = mView.getClass().getDeclaredFields();
        for (Field field : fields) {
            InjectPresenter annotation = field.getAnnotation(InjectPresenter.class);
            Class<? extends BasePrsenter> presenterClazz = null;
            if (annotation != null) {
                presenterClazz = (Class<? extends BasePrsenter>) field.getType();
                try {
                    BasePrsenter basePrsenter = presenterClazz.newInstance();
                    basePrsenter.onAttachPresenter(mView);
                    field.setAccessible(true);
                    //赋值
                    field.set(mView, basePrsenter);
                    prsenterList.add(basePrsenter);

                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                }


            }
        }

    }

    @Override
    public void unbindPresenter() {
        if (prsenterList == null) {
            return;
        }
        for (BasePrsenter basePrsenter : prsenterList) {
            basePrsenter.onDetachPresenter();
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    private void destory() {
        Log.e(TAG, "destory: ");
        unbindPresenter();
    }
}
